﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace EBA.WindowsServices
{
    [Serializable]
    public class RemotingController : MarshalByRefObject
    {
        public RemotingController(IWindowsService windowService)
        {
            this.WindowService = windowService;
        }

        IWindowsService WindowService { get; set; }

        IWindowsServiceOutput _LocalOuput;
        public void SwitchOutput(IWindowsServiceOutput remoteOutput)
        {
          //  Debugger.Launch();
            if (this.WindowService != null)
            {
                if (remoteOutput == null)
                {
                    if (this._LocalOuput is WindowsServiceOutput)
                    {
                        var localOutput = this._LocalOuput as WindowsServiceOutput;
                        localOutput.RemoteOutput = null;
                    }
                    else
                    {
                        this.WindowService.Output = this._LocalOuput;
                    }
                }
                else
                {
                    this._LocalOuput = this.WindowService.Output;
                    if (this._LocalOuput is WindowsServiceOutput)
                    {
                        var localOutput = this._LocalOuput as WindowsServiceOutput;
                        localOutput.RemoteOutput = remoteOutput;
                    }
                    else
                    {
                        this.WindowService.Output = remoteOutput;
                    }
                }

              //  Debugger.Launch();
                if (remoteOutput != null)
                {
                    remoteOutput.WriteLine(OutputLevel.Trace, "[{0}] is ready.",this.WindowService.Name);
                }
            }
            else
            {
                if (remoteOutput != null)
                {
                    remoteOutput.WriteLine(OutputLevel.Error, "The remote console is stopped.");
                }
            }
        }

        public void ShowMgmtWindow()
        {

        }

        public override object InitializeLifetimeService()
        {
            return null;
        }
    }
}
